package com.shenfa.action.work;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.gmc.util.config.NetReader;
import net.gmc.util.netserver.NetServerUtil;
import net.gmc.util.netserver.command.CommandMaker;
import net.gmc.util.netserver.control.NetServerFlowControl;
import net.gmc.util.netserver.flow.NetServerFlowInterface;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.shenfa.bean.CheckRuleData;
import com.shenfa.bean.PaperInfo;
import com.shenfa.bean.Template;
import com.shenfa.bean.Person;
import com.shenfa.bean.work.BillEList;
import com.shenfa.bean.work.BillPList;
import com.shenfa.bean.work.Check;
import com.shenfa.bean.work.ComposeLog;
import com.shenfa.bean.work.Watch;
import com.shenfa.bean.work.WatchState;
import com.shenfa.bean.work.XmlLog;
import com.shenfa.bean.xml.PointInfo;
import com.shenfa.bean.xml.UserBase;
import com.shenfa.dao.PaperDao;
import com.shenfa.dao.xml.MakeXmlDao;
import com.shenfa.service.compose.MakeComposeService;
import com.shenfa.service.work.XmlLogService;
import com.shenfa.service.xml.MakeXmlService;

import com.shenfa.util.Config;
import com.shenfa.util.ReadShowFile;
import com.shenfa.util.ResultObject;

public class WorkAction extends ActionSupport implements ServletResponseAware {

	private static final long serialVersionUID = 1L;
	// service
	@Autowired
	private XmlLogService xmlLogService;
	@Autowired
	private PaperDao paperDao;
	@Autowired
	private MakeXmlDao makeXmlDao;
	@Autowired
	private MakeComposeService makeComposeService;
	@Autowired
	private MakeXmlService makeXmlService;
	// 返回结果集对象
	public JSONObject result;
	// 分页，第几条数据
	private int start;
	// 每页显示数据条数
	private int limit;
	// 总记录条数
	private int total=0;
	// 接收页面ComposeLog数据
	private ComposeLog logdata;
	// 接收页面XmlLog数据
	private XmlLog xmldata;
	// 接收页面合成监控状态数据
	private WatchState watchState;

	private String listlog;
	
	private Check checkVJAData;

	private BillPList billp;

	private BillEList bille;

	private String billType;

	private HttpServletRequest request;

	private HttpServletResponse response;

	private Map<String, String> paramMap;

	private static Logger log = Logger.getLogger(WorkAction.class);

	private String pdfPath;
	private String typeflag;
	private String filename;
	private String period;

	/**
	 * XML生成日志
	 */
	@SuppressWarnings("unchecked")
	public String xmlLogGridList() {
		if (null != xmldata) {
			log.debug(xmldata.toString() + ",start=" + start + ",limit="
					+ limit);
		}
		List<XmlLog> list = new ArrayList<XmlLog>();
		list = xmlLogService.doGridList(xmldata, start, limit);
		total = (Integer) xmlLogService.doPagTotal(xmldata);
		result = ResultObject.build("0", list);
		result.put("total", total);
		return SUCCESS;
	}

	/**
	 * 查询账单合成后的XMLLog信息（条件登录用户ID，账期）
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String queryXmlLog() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		Object obj = request.getSession().getAttribute("login");
		if (null == obj)
			return null;
		Person person = (Person) obj;
		paramMap = new HashMap<String, String>();
		paramMap.put("typeflag", typeflag);
		paramMap.put("personid", person.getId());
		paramMap.put("period", makeXmlDao.getConfig().get("PERIOD"));
		List<Map<String, String>> list = xmlLogService.queryXmlLog(paramMap,
				start, limit);
		int total = makeXmlDao.queryTotleXmlLog(paramMap);
		result = ResultObject.build("0", list);
		result.put("Total", total);
		return SUCCESS;
	}

	/**
	 * 查询账单合成日志
	 */
	@SuppressWarnings("unchecked")
	public String composeLogGridList() {
		if (null != logdata) {
			log.debug(logdata.toString() + ",start=" + start + ",limit="
					+ limit);
		}
		List<ComposeLog> list = new ArrayList<ComposeLog>();
		list = xmlLogService.docomposeLogList(logdata, start, limit);
		total = (Integer) xmlLogService.doComPagTotal(logdata);
		result = ResultObject.build("0", list);
		result.put("total", total);
		return SUCCESS;
	}

	/**
	 * 分发账单(修改账单状态)
	 */
	public String send() {
		log.debug("listlog=" + listlog);
		int type = xmlLogService.upd(listlog);
		if (type == 1) {
			result = ResultObject.build(String.valueOf(type), "分发成功！");
		} else {
			result = ResultObject.build(String.valueOf(type), "操作失败！");
		}
		return SUCCESS;
	}

	/**
	 * 合成监控状态信息列表
	 */
	@SuppressWarnings("unchecked")
	public String watchGridList() {
		List<WatchState> list = new ArrayList<WatchState>();
		list = xmlLogService.watchStateGridList(watchState, start, limit);
		result = ResultObject.build("0", list);
		total = (Integer) xmlLogService.doWatchlenTotal(watchState);
		result.put("total", total);
		return SUCCESS;
	}

	/**
	 * 查询抽样所需的电子/纸质合成日志
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String sampleComposeLog() {
		if (null != logdata) {
			log.debug(logdata.toString() + ",start=" + start + ",limit="
					+ limit);
		}
		List<ComposeLog> list = new ArrayList<ComposeLog>();
		list = xmlLogService.doSampleComposeLog(logdata, start, limit);
		result = ResultObject.build("0", list);
		total = (Integer) xmlLogService.doComPagTotal(logdata);
		result.put("total", total);
		return SUCCESS;
	}

	/**
	 * 查询watch
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String queryWatch() {
		List<Watch> list = new ArrayList<Watch>();
		list = xmlLogService.queryWatch(start, limit);
		result = ResultObject.build("0", list);
		total = (Integer) xmlLogService.doPagWatch();
		result.put("total", total);
		return SUCCESS;
	}

	/**
	 * 数据验证——模板
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String queryTemp() {
		List<Template> list = new ArrayList<Template>();
		list = xmlLogService.queryCheckData(start, limit);
		result = ResultObject.build("0", list);
		total = (Integer) xmlLogService.totalCDTemp();
		result.put("total", total);
		return SUCCESS;
	}

	/**
	 * 数据验证——规则
	 * 
	 * @return
	 */
	public String queryRule() {
		List<CheckRuleData> list = new ArrayList<CheckRuleData>();
		list = xmlLogService.queryArea(period,start, limit);
		result = ResultObject.build("0", list);
		//total = (Integer) xmlLogService.queryRuleTotalPage();
		//result.put("total", total);
		return SUCCESS;
	}
	
	/**
	 * 数据验证——V+,AllReady
	 * 
	 * @return
	 */
	public String queryVJACheck(){
		List<Check> list = new ArrayList<Check>();
		list = xmlLogService.queryVJACheck(checkVJAData, start, limit);
		result = ResultObject.build("0", list);
		//total = (Integer) xmlLogService.queryCheckPage(checkVJAData);
		//result.put("total", total);
		return SUCCESS;		
	}

	/**
	 * 获取默认账期
	 * 
	 * @return
	 */
	public String getPeriod(){
		period = xmlLogService.getPeriod();
		result = ResultObject.build("0", period);
		return SUCCESS;	 
	}
	
	/**
	 * 数据验证——积分
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String queryJFCheck(){
		List<PointInfo> list= new ArrayList<PointInfo>();
		if(null!=period&&!"".equals(period)){
			period = period.substring(0,10).replaceAll("-", "");
			xmlLogService.addJFCheck(period);
			xmlLogService.delJFCheck(period);
			list = xmlLogService.queryJFCheck(period, start, limit);
			total = (Integer) xmlLogService.queryJFCheckPage(period);
		}
		result = ResultObject.build("0", list);
		result.put("total", total);
		return SUCCESS;
	}
	
	/**
	 * 全部通过
	 * 
	 * @return
	 */
	public String updateCheck(){
		String dat = "";
		if(null!=checkVJAData.getPeriod()&&!"".equals(checkVJAData.getPeriod())){
			dat = checkVJAData.getPeriod().substring(0,10).replaceAll("-", "");				
		}
		int a = xmlLogService.updateCheck(dat);
		result = ResultObject.build(""+a, a);		
		return SUCCESS;
	}
	
	/**
	 * 账单预印纸验证
	 * 
	 * @return
	 */
	public String queryYYZ(){
		List<Check> list = new ArrayList<Check>();
		if(null!=period&&!"".equals(period)){
			period = period.substring(8,10);				
		}
		list = xmlLogService.queryYYZ(period);
		result = ResultObject.build("0", list);
		return SUCCESS;
	}
	
	/**
	 * 账单城市验证
	 * 
	 * @return
	 */
	public String queryCity(){
		List<UserBase> list = new ArrayList<UserBase>();
		if(null!=period&&!"".equals(period)){
			period = period.substring(0,10).replaceAll("-", "");				
		}
		list = xmlLogService.queryCity(period,start, limit);
		result = ResultObject.build("0", list);
		//total = (Integer) xmlLogService.queryCityPage();
		//result.put("total", total);
		return SUCCESS;
	}
	
	/**
	 * 更新城市为空的账单
	 * 
	 * @return
	 */
	public String updateCity(){
		if(null!=period&&!"".equals(period)){
			period = period.substring(0,10).replaceAll("-", "");				
		}
		int a = xmlLogService.updateCity(period);
		result = ResultObject.build(""+a, a);		
		return SUCCESS;
	}
	
	/**
	 * 抽样操作
	 */
	@SuppressWarnings("unchecked")
	public String sample() {
		if (null != billp) {
			log.debug("filename=" + billp.getFilename() + ",card_no="
					+ billp.getCard_no() + ",period=" + billp.getPeriod()
					+ ",paper_no=" + billp.getPaper_no());
		}
		ArrayList<HashMap<String, Object>> dataList = new ArrayList<HashMap<String, Object>>();

		// 判断账单类型1为纸质，2为电子
		if (billType.equals("1") || "1" == billType) {
			// 纸质账单的合成
			List<BillPList> billps = xmlLogService.queryBillp(billp, start,
					limit);
			total = (Integer) xmlLogService.queryBillpTotal(billp);

			log.debug("billps size is: " + billps.size());

			if (0 < billps.size()) {
				for (int j = 0; j < billps.size(); j++) {
					int pageFlag = billps.get(j).getPage();
					if (-1 == pageFlag) {
						result = ResultObject.build(String.valueOf(pageFlag),
								"页数不能为0！");
					} else {
						HashMap<String, Object> dataMap = new HashMap<String, Object>();
						dataMap.put("wfd", Config.getValue("wfd").toString());
						dataMap.put("strTnoPath", Config.getValue("tno.path")
								.toString()
								+ billp.getBusinpnt_no()
								+ "/"
								+ billp.getFilename() + ".tno");
						dataMap.put("strType", "0");
						dataMap.put("strIndex", billps.get(j).getAccount());
						dataMap.put("templateFlag", "1");

						HashMap<String, Object> xmlDataMap = new HashMap<String, Object>();
						xmlDataMap = new HashMap<String, Object>();
						List<PaperInfo> listPInfo = paperDao
								.queryPaperInfoBypaperNo(billps.get(j)
										.getPaper_no());
						if (0 < listPInfo.size())
							for (int i = 0; i < listPInfo.size(); i++) {
								if (null == listPInfo.get(i).getFront()
										|| listPInfo.get(i).getFront()
												.equals("")) {
								} else {
									xmlDataMap.put("prePaperPath" + (i + 1),
											listPInfo.get(i).getFront());
								}
							}

						dataMap.put("prePaperPath", xmlDataMap);
						dataMap.put("e", CommandMaker.OUTPUT_TYPE_SAMPLE);
						dataMap.put("f",
								Config.getValue("path.pdf").toString()
										+ billps.get(j).getAccount() + "_"
										+ System.currentTimeMillis() + ".pdf");
						dataMap.put("c", Config.getValue("create.job")
								.toString());
						dataMap.put("warningconfig",
								Config.getValue("warningconfig").toString());
						dataList.add(dataMap);
						log.debug("dataList set dataMap Object.");
					}
				}
				try {
					log.debug("init net server config start.");
					NetReader.init();
					log.debug("init net server config finish.");
					NetServerUtil nsu = new NetServerUtil(dataList);
					log.debug("init NetServerUtil start.");
					NetServerFlowControl control = nsu.start();
					log.debug("init NetServerUtil finish.");
					NetServerFlowInterface runnerFlow = null;
					log.debug("rulePDF:NetServerFlowSize="
							+ control.getNetServerFlowSize());
					for (int j = 0; j < control.getNetServerFlowSize(); j++) {
						runnerFlow = control.getNetServerFlow(j);
						boolean runSucc = runnerFlow.runSuccess();
						if (!runSucc) {
							if (runnerFlow.lastJobMessage().contains(
									"0030:Nothing to print.")) {
								log.debug("Nothing to print. fileindex flag write is [already pass]");
							}
						}
					}
				} catch (Exception e) {
					log.error(e);
					result = ResultObject.build("0", e.getMessage());
				}
			}
			result = ResultObject.build("0", dataList);
			result.put("total", total);
		} else {
			// 电子账单的处理
			List<BillEList> billEs = xmlLogService.queryBille(bille, start,
					limit);
			total = (Integer) xmlLogService.queryBilleTotal(bille);
			log.debug("BillEList size is:" + billEs.size());
			if (0 < billEs.size()) {
				for (int i = 0; i < billEs.size(); i++) {
					if (null == billEs.get(i).getPath()
							|| billEs.get(i).getPath().equals("")) {

					} else {
						HashMap<String, Object> dataMap = new HashMap<String, Object>();
						dataMap.put(
								"HTMLpath",
								Config.getValue("html.product.path").toString()
										+ billEs.get(i).getPeriod()
												.substring(0, 4)
										+ "/"
										+ billEs.get(i).getPeriod()
												.substring(5, 7)
										+ "/"
										+ billEs.get(i).getPeriod()
												.substring(8, 10) + "/"
										+ billEs.get(i).getCard_id() + "/"
										+ billEs.get(i).getPath());
						log.debug("HTMLpath is :" + dataMap.get("HTMLpath"));
						dataList.add(dataMap);
					}
				}
			}
			result = ResultObject.build("0", dataList);
			result.put("total", total);
		}

		return SUCCESS;
	}

	/**
	 * 读PDF文件
	 * 
	 * @return
	 */
	public String showPDF() {
		if (null != pdfPath) {
			ReadShowFile.read(pdfPath, response, true);
		}
		return null;
	}
	
	/**
	 * 生成XML文件、合成账单
	 * @return
	 */
	public String make_composeXml() {
		HashMap<String, String> map = new HashMap<String, String>();
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		Object obj = request.getSession().getAttribute("login");
		if (null == obj)
			return null;
		Person person = (Person) obj;
		if(null != filename){
			map.put("fileName", filename);
			map.put("period", period);
			try {
				String type = makeComposeService.makeCompose1(map);
				this.returnMsg(type);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{	//特殊账单合成
			map.put("personNo", person.getId());
			//生成XML
			makeXmlService.make(person.getId());
			try {
				makeComposeService.makeCompose(person.getId());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return SUCCESS;
	}
	
	private void returnMsg(String msg){
		response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter pw;
		try {
			pw = response.getWriter();
			pw.print(msg);
			pw.flush();
			pw.close();
			response.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setStart(int start) {
		this.start = Math.abs(start);
	}

	public void setLimit(int limit) {
		this.limit = Math.abs(limit);
	}

	public ComposeLog getLogdata() {
		return logdata;
	}

	public void setLogdata(ComposeLog logdata) {
		this.logdata = logdata;
	}

	public XmlLog getXmldata() {
		return xmldata;
	}

	public void setXmldata(XmlLog xmldata) {
		this.xmldata = xmldata;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public String getListlog() {
		return listlog;
	}

	public void setListlog(String listlog) {
		this.listlog = listlog;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public BillPList getBillp() {
		return billp;
	}

	public void setBillp(BillPList billp) {
		this.billp = billp;
	}

	public void setServletResponse(HttpServletResponse arg0) {
		this.response = arg0;
	}

	public BillEList getBille() {
		return bille;
	}

	public void setBille(BillEList bille) {
		this.bille = bille;
	}

	public String getBillType() {
		return billType;
	}

	public void setBillType(String billType) {
		this.billType = billType;
	}

	public WatchState getWatchState() {
		return watchState;
	}

	public void setWatchState(WatchState watchState) {
		this.watchState = watchState;
	}

	public void setPdfPath(String pdfPath) {
		this.pdfPath = pdfPath;
	}

	public String getTypeflag() {
		return typeflag;
	}

	public void setTypeflag(String typeflag) {
		this.typeflag = typeflag;
	}

	public Check getCheckVJAData() {
		return checkVJAData;
	}

	public void setCheckVJAData(Check checkVJAData) {
		this.checkVJAData = checkVJAData;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public void setPeriod(String period) {
		this.period = period;
	}

	
}
